package com.wisezone.workflow.dao.hibernate;

import com.wisezone.common.Pagination;
import com.wisezone.common.dao.impl.BaseHibernateDaoImpl;
import com.wisezone.workflow.bean.search.WorkFlowSearch;
import com.wisezone.workflow.dao.WfProcessInstanceDao;
import com.wisezone.workflow.exception.WfDaoException;

/**
 * hiberante 流程实例实现类
 * 
 * @author tss 2009-09-05
 * 
 */
public class WfProcessInstanceDaoImpl extends BaseHibernateDaoImpl implements
		WfProcessInstanceDao {

	public WfProcessInstanceDaoImpl() {
		super();
	}

	/**
	 * 当前流程实例相关信息查询
	 * @param hql
	 * @param searchEntity
	 * @return
	 * @throws Exception
	 */
	public<T> Pagination<T> listFormByPage(WorkFlowSearch searchEntity) throws WfDaoException{
		
		String hql = searchEntity.getHql();
		
		//Hql 处理
		int whereIndex = hql.indexOf("where");
		String mainHql = hql;
		String whereHql = " and ti.processInstId = t.procsssInstId ";
		if(whereIndex != -1){
			mainHql = hql.substring(0,whereIndex);
			whereHql = whereHql + " and "+ hql.substring(whereIndex+5,hql.length());
		}
		StringBuffer sb = new StringBuffer();
		sb.append(mainHql);
		sb.append(",WfActivityInstance ti,WfProcessInstance t2 ");
		
		//已操作
		sb.append("where ti.processInstId = t2.id and ((ti.userId is not null and ti.userId = :actorId " );
		
		//已操作过滤重复记录
		sb.append(" and ti.createTime in (select max(ti2.createTime) from WfActivityInstance ti2 where ti2.userId = ti.userId and ti2.processInstId = ti.processInstId ))");
		
		//未操作
		sb.append(" or (ti.assignee is  null and ti.id in ");
		
		//未操做过滤任务人员条件
		sb.append("(select tu.activityId from WfActivityInstUser tu where ((tu.userId is null and tu.userGroupId in ( :actorGroupIds ) ) or (tu.userId is not null and tu.userId = :actorId )))))");
		
		sb.append(whereHql);
		
		sb.append(" order by case when ti.endTime is null then 1 else 2 end ,t.startTime desc");
		
	    hql = "select new WorkFlowForm(t,ti,t2) "+sb.toString();
	    
	    searchEntity.setHql(hql);
	    
	    return super.listFormByPage(searchEntity);

	}

}